//
// 展示c的几个头文件使用 未包含C++11增加的内容。
//  根据 http://www.cplusplus.com/reference/
//
#include<iso646.h>
void iso646_used()
{
	//该头文件定义了11个宏
	//　单　&&　｜｜　～  [and\or\compl]
	//　双　！＝　＆＝　｜＝　＾＝  [not_eq\and_eq\or_eq\xor_eq]
	//      !     &    |     ^    [not\and\or\xor]
	cout << "0 xor 1 = 0^1= " <<(0 xor 1) << endl;
	//滴滴笔试题：
	cout <<( 1 ^ (1<<31>>31) )<< "是结果。"<<endl;
	//4字节存储、（负数）反码：除符号位外，逐位取反。补码：反码加一
	//原反码转换：除符号位外，逐位取反，末位加1.（负数）
	cout<<"int的字节数："<<sizeof(int)<<endl;
	int x = -1;
	unsigned int y = 2;
	cout <<"-1-2="<< ((x > y) ? "正数" : "负数") << endl;
}
#include<time.h>
double consumed_time()
{
	double n = 0;
	for (int i = 1; i < 10000; i++){
		for (int j = 1; j < 100000; j++){
			if (i==j){
				n = sqrt(i * j);
			}
			else{
				n = i*j;
			}
		}
	}
	return n;
}
void time_used()  //计算程序运行时间
{
	clock_t t;
	t = clock();
	double n=consumed_time();
	t = clock() - t;
	cout << "the consumed_time() calling consumed time is:" << t << n << endl;
	cout << "the seconeds is:" << float(t) / CLOCKS_PER_SEC << endl;
}
void time_used1()  //time_t 用来计算日期
{
	time_t t1, t2;
	double seconds;
	t1 = time(NULL);
	double n=consumed_time();
	t2 = time(NULL);
	seconds = difftime(t2, t1);   //等价于 (t2-t1)

	cout <<"计算结果"<< n << "，耗时为："  << seconds << "s" << endl;
}
void get_time()//显示当前时间
{
	time_t timer = time(NULL);
	char buffer[80];
	ctime_s(buffer, 80, &timer);
	puts(buffer);
	//cout <<"当前时间为："<< ctime(&timer) << endl;
	time_t rawtime;
	time(&rawtime);
	//timeinfo=localtime(&rawtime); //不安全编译通不过
	//cout << "当前时间为：" << asctime(timeinfo) << endl;
	//timeinfo = gmtime(&rawtime);  //同样不安全
	//cout << "beijing time is:" << timeinfo->tm_hour << ':' << timeinfo->tm_min << endl;
}
//#define NDEBUG   //定义在断言头之前 所有断言失效。
#include<assert.h>
void assert_used()
{
	int i = 1;
	assert(i == 1);
	//assert(i == 0); //其实就是验证条件为真
	cout << i << endl;
}
#include<ctype.h>
void ctype_used()
{
	// 返回值都是int
	cout << "isalnum('d3') " << (isalnum('d3') ? "true" : "false") << endl;
	cout << "isalpha('d') " << (isalpha('d') ? "true" : "false") << endl;
	cout << "isblank(' ') " << (isblank(' ') ? "true" : "false") << endl;
	cout << "iscntrl('p') " << (iscntrl('p') ? "true" : "false") << endl;
	cout << "isdigit('3') " << (isdigit('3') ? "true" : "false") << endl;
	//是否有图形表示
	cout << "isgraph('d3') " << (isgraph('d3') ? "true" : "false") << endl;
	cout << "islower('d') " << (islower('d') ? "true" : "false") << endl;
	cout << "isprint('d3') " << (isprint('d3') ? "true" : "false") << endl;
	cout << "ispunct('&') " << (ispunct('&') ? "true" : "false") << endl;
	cout << "isspace(' ') " << (isspace(' ') ? "true" : "false") << endl;
	cout << "isupper('P') " << (isupper('P') ? "true" : "false") << endl;
	//是否为16进制数字
	cout << "isxdigit('f') " << (isxdigit('f') ? "true" : "false") << endl;
	cout << "toupper('p') " << char(toupper('p') ) << endl;
	cout << "tolower('M') " << char(tolower('M') ) << endl;
}
// errno.h  定义了错误值
// float.h  定义了浮点值的实现情况
//limits.h  定义了各类型的取值范围大小【已学过】
#include<locale.h>
void locale_used()
{
	//本地化或国际化库：更改货币\日期等 的显示方式
	struct lconv * lc;
	setlocale(LC_ALL, NULL);
	lc = localeconv();
	cout << "当前货币符号是：" << lc->currency_symbol << endl;
	cout << "当前分隔符号是：" << lc->mon_thousands_sep << endl;
	cout << "当前符号是：" << lc->decimal_point << endl;
	cout << "当前符号是：" << lc->frac_digits << endl;
	cout << "当前符号是：" << lc->grouping << endl;
	cout << "当前符号是：" << lc->mon_decimal_point << endl;
	cout << "当前符号是：" << lc->mon_grouping << endl;
	setlocale(LC_ALL, "");
	lc = localeconv();
	cout << "当前货币符号是：" << lc->currency_symbol << endl;
	cout << "当前分隔符号是：" << lc->mon_thousands_sep << endl;
	cout << "当前符号是：" << lc->decimal_point << endl;
	cout << "当前符号是：" << lc->frac_digits << endl;
	cout << "当前符号是：" << lc->grouping << endl;
	cout << "当前符号是：" << lc->mon_decimal_point << endl; 
	cout << "当前符号是：" << lc->mon_grouping << endl;
	cout << "当前符号是：" << lc->negative_sign << endl;
	cout << "当前符号是：" << lc->n_cs_precedes << endl;
	cout << "当前符号是：" << lc->n_sep_by_space << endl;
	cout << "当前符号是：" << lc->n_sign_posn << endl;
	cout << "当前符号是：" << lc->thousands_sep << endl;
}
#include<math.h>
void math_used()
{
	float number = 9;
	if (number == NAN){//NAN:not a number
		cout << "不是一个数字\n";
	}
	else{
		cout << "是一个数字\n";
	}
	//Trigonometric functions 三角函数
	cout << "cos(60)=" << cos(60.0 / 180 * PI)<<endl;
	cout << "sin(60)=" << sin(60.0 / 180 * PI) << endl;
	cout << "tan(60)=" << tan(60.0 / 180 * PI) << endl; 
	cout << "acos(60)=" << acos(60.0 / 180 * PI) << endl; 
	cout << "asin(60)=" << asin(60.0 / 180 * PI) << endl;
	cout << "atan(60)=" << atan(60.0 / 180 * PI) << endl;
	cout << "atan2(60.0)=" << atan2(10.0,-10.0)*180/PI << endl;
	cout << "cosh(60)=" << cosh(60.0 / 180 * PI) << endl;
	cout << "sinh(60)=" << sinh(60.0 / 180 * PI) << endl;
	cout << "tanh(60)=" << tanh(60.0 / 180 * PI) << endl;
	//Exponential and logarithmic functions 指数和对数
	cout << "e 的1次方是："<<exp(1)<<endl;
	cout << "0.95*2^4=" << ldexp(0.95, 4) << endl;//frexp()是逆运算。
	cout << "log(5.5)的自然对数：" << log(5.5) << endl;
	cout << "log10(1000)=" << log10(1000) << endl;
	double num = 3.1415;
	double zheng, xiao;
	xiao = modf(num, &zheng);
	cout << "拆分3.1415：" << zheng << " " << xiao << endl;
	cout << "7的三次方：" << pow(7, 3) << endl;
	cout << "7的2.5次方：" << pow(7, 2.5) << endl;
	cout << "64开根号：" << sqrt(64) << endl;
	cout << "7.3/3的余数：" << fmod(7.3, 3) << endl;
	cout << "5.3上取整：" << ceil(5.3) << endl;
	cout << "5.5下取整：" << floor(5.5) << endl;
	cout << "绝对值：-3.14=" << fabs(-3.14) << " " << abs(-3.14) << endl;
}
#include<stdarg.h>
void printfloats(int n,...)
{
	int i;
	double val;
	puts("print floats:");
	va_list v1;
	va_start(v1, n);
	for (i = 0; i < n; i++){
		val = va_arg(v1, double);
		cout << '[' << val << ']' << endl;
	}
	va_end(v1);
}
void stdarg_used()
{
	// comma:,three dots: ...  变参处理
	// 感觉不如指针方便
	printfloats(3, 3.14, 2.7182, 1.628);

}
#include<stddef.h>
void stddef_used()
{
	//define ptrdiff_t指针差  size_t  
	//macro  offsetof偏移值   NULL
	struct fst{
		char a;
		int b[10];
		char c;
		int d;
	};
	cout << (int)offsetof(struct fst, a) << " ,"
		<< (int)offsetof(struct fst, b) << " ,"
		<< (int)offsetof(struct fst, c) << " ,"
		<< (int)offsetof(struct fst, d) << endl;
}
#include<signal.h>
sig_atomic_t signaled = 0;
void my_handler(int param)
{
	signaled = 1;
}
void signal_used()
{
	//信号处理及设置SIGABRT（abort） SIGFPE（浮点异常） SIGILL（非法指令） SIGINT 中断SIGSEGV（Segmentation Violation） SIGTERM（Terminate）
	// SIGDFL默认 SIGIGN忽略
	signal(SIGINT, my_handler);
	raise(SIGINT);
	cout << "signaled is " << signaled << endl;
}
#include<setjmp.h>
jmp_buf jb;
void c()
{
	cout << "call c()" << endl;
	longjmp(jb, 1);
}
void b()
{
	c();
	cout << "call b()" << endl;
}
void a()
{
	b();
	cout << "call a()" << endl;
}
void setjmp_used()
{
	//非本地跳转1、跳出多个函数嵌套，2、异常处理,别再C++中使用
	if (setjmp(jb) == 0){
		a();
	}
	cout << "after a()" << endl;
}
#include<string.h>  // c的串操作
void string_used()
{
	//--copy--------------
	struct{
		char* name;
		int age;
	}person1,person2;
	person1.name = "asdkfslljoiu";
	person1.age = 22;
	memcpy(&person2,&person1,sizeof(person1));//person1 copy to person2
	cout << person2.name << " " << person2.age << endl;

	char str[] = "memmove can be very useful.........";
	memmove(str + 20, str + 15, 11);
	puts(str);

	char str2[40];
	strcpy_s(str2, "我寂寞寂寞就好0田馥甄");
	puts(str2);

	char str1[] = "to be or not to be!";
	strncpy_s(str2,str1,sizeof(str2));  //控制长度的赋值
	puts(str2);
	//----链接 concatenation------------
	strcat_s(str2,"harry port");
	puts(str2);
	//----比较-------------------------
	if (strcmp("asd","asd")){
		cout << "不匹配！" << endl;
	}
	else{
		cout << "匹配！" << endl;
	}
	//-----搜索-----------------------
	char* pch = strstr(str2,"be");// 串查找
	strncpy(pch,"oo",2);
	puts(str2);

	char keys[] = "1234567098";
	int i = strcspn(str2,keys);//出现位置
	cout << "第一个数字出现在：" << i << endl;

	pch=strchr(str2,'r');
	cout << pch-str2+1 <<"是r出现的位置"<< endl;// pch是要搜字符的地址
	//---------qita--------
	//memset() streror() 
	cout << strlen("asd") <<"实际串长："<<sizeof("asd")<< endl;
	//also have :NULL  、size_t.
}
#include<stdlib.h>
void stdlib_used()
{
	cout << atof("3.1415962") + 11 << endl;
	cout << atoi("123") - 12 << endl;
	cout << atol("12345567") << endl;
	srand(100);
	cout <<"随机数："<< rand() << endl;
	//---------------------
	int* pdata = (int*)calloc(10,sizeof(int));//初始化为0
	assert(pdata!=NULL);
	int* pdata1 = (int*)malloc(5*sizeof(int));
	assert(pdata1!= NULL);
	int* pdata2 = (int*)realloc(pdata1, 10 * sizeof(int));//并不是扩大多少，而是扩大后的大小是多少。
	assert(pdata2 != NULL);
	for (int i = 0; i < 10; i++){
		pdata[i] = rand()%100;
		pdata2[i] = rand()%100;
	}
	for (int i = 0; i < 10; i++){
		//cout << *pdata++ << " - " << *pdata2++ << endl;
		cout << pdata[i] << " - " << pdata2[i] << endl;
	}
	cout << "recalloc()内的指针地址" << pdata1 << endl;
	cout << "recalloc()外的指针地址" << pdata2 << endl;
	free(pdata);
	//free(pdata1); //会出bug
	free(pdata2);
	//----------------------------------
	//abort();  //中断进程
	//atexit(math_used);  //程序退出时执行
	//exit(0);  //程序退出
	//----------------------------------
	char* path = getenv("JAVA_HOME");
	cout << path << " is java path" << endl;//为什么没有*？？？？
	cout << "返回值是" << system("dir") << endl;
	cout << "整型-11绝对值：" << abs(-11) << endl;
	div_t result = div(33, 5);
	cout << "33/5=" << result.quot << "余" << result.rem << endl;
	//labs : long int abs() version
	//----多字节处理------------------------
	//mblen() mbtowc()  wctomb() mbstowcs() wcstombs()
	cout << EXIT_FAILURE << " " << EXIT_SUCCESS << " " << NULL << endl;
	cout << "最大随机值：" << RAND_MAX << endl;
	cout << "多字节最大值：" << MB_CUR_MAX << endl;
	//--------排序搜索-------------------------
	//bsearch();
	//qsort();
}
#include<stdio.h>
void used1()//not work
{
	FILE* file2 = fopen("temp.txt", "w");
	fputs("this is an apple.", file2);
	fseek(file2, 9, SEEK_SET);
	fputs(" sam", file2);
	fclose(file2);
}
void used2()
{
	freopen("temp.txt", "a+", stdout);
	cout << "\n以下内容将被写入文件。" << endl;
	int i = 0;
	//scanf("输入一个整数：%d", &i);
	printf("输入的数值是：%d\n", 3);
	fputc('n', stdout);
	puts("\n puts 方式输出。\n");
	putchar('a');
	putc('l', stdout);  //第二个参数为FILE* 类型
	fclose(stdout);
}
void used3()
{
	FILE* file1 = fopen("temp.txt", "a+");//w:write r:read a:add +:update
	assert(file1 != NULL);
	fputs("siqianming .***\n", file1);
	fprintf(file1, "姓名-%d:[%s]", 001, "琼生");
	//fscanf(file1, "%s", &i);  //形式相同
	fflush(file1);
	fclose(file1);
}
void used4()
{
	//临时文件、
	FILE* pfile = tmpfile();
	char buffer[256] = "这是一个临时文件，文件关闭立即失效。over.\n";
	fputs(buffer, pfile);
	fputs("this is a good idea! use cin\n", pfile);
	rewind(pfile);
	while (!feof(pfile)){
		if (fgets(buffer, 256, pfile) == NULL)break;
		fputs(buffer, stdout);
	}
	fclose(pfile);
	//生成临时文件名
	char* name = tmpnam(NULL);
	cout << name << " is the temp file name.\n";
	//ostream  999line  error
}
void used5()
{
	//文件操作-------------
	rename("food.txt", "book.txt");
	if (remove("book.txt") != 0){
		perror("error deleting file.");
	}
	else{
		puts("success remove the file!");
	}
}
void used6()
{
	char buffer1[BUFSIZ];
	FILE* pfile1 = fopen("myfile1.txt", "a+");
	FILE* pfile2 = fopen("myfile2.txt", "a+");
	setbuf(pfile1, buffer1);
	fputs("\nthis is a buffer stream1", pfile1);
	setbuf(pfile2, NULL);//设置缓冲区
	fputs("\nthis is a buffer stream2", pfile2);
	//两个文件都写入成功，再关闭之前？？？ 
	//char str[256];
	//gets(str);
	//cout << str << endl;
	//putchar(getchar());
	//putc(getc(stdin), stdout);
	//fputc(fgetc(stdin), stdout);

	long size = ftell(pfile1);//获得位置
	fpos_t position;
	fgetpos(pfile1, &position);//获得位置
	fsetpos(pfile1, &position);
	rewind(pfile1);
	std::cout << "ftell and pposition:" << size << "  " << position << endl;

	fclose(pfile1);
	fclose(pfile2);

	remove("myfile1.txt");
	remove("myfile2.txt");
}
void stdio_used()
{//单独都能用，去掉注释有bug  cout怎么到文件里了？
	//used1();
	//used2();
	//used3();
	//used4();
	//used5();
	//used6();
	//sscanf()和sprintf() 串输入和串输出
	//ungetc('#',stdin); //用#号替换getc（）到的字符。
	FILE* file6;
	char buffee[] = {'x','y','k'};
	file6 = fopen("myfile.bin","wb");
	fwrite(buffee,sizeof(char),sizeof(buffee),file6);//快数据读写
	fclose(file6);
	remove("myfile.bin");

	FILE* file6;
	char buffee[] = {'x','y','k'};
	file6 = fopen("myfile.bin","wb");
	fwrite(buffee,sizeof(char),sizeof(buffee),file6);//快数据读写
	fclose(file6);
	remove("myfile.bin");
	cout << "BUFSIZ:" << BUFSIZ << endl;
	cout << "EOF:" << EOF << endl;
	cout << "FILENAME_MAX:" << FILENAME_MAX << endl;
	cout << "FOPEN_MAX:" << FOPEN_MAX << endl;
	cout << "L_tmpnam:" << L_tmpnam << endl;
	cout << "NULL" << NULL << endl;
	cout << "TMP_MAX:" << TMP_MAX << endl;
	perror("the following error happend.");
	if (ferror(file6)){
		cout << "there is a error in file6." << endl;
	}
	else{
		cout << "there is no error." << endl;
	}
	//Resets both the error and the eof indicators of the stream.
	clearerr(file6);
	if (feof(file6)){
		cout << "到达文件末尾。" << endl;
	}
	else{
		cout << "未到达文件末尾。" << endl;
	}
}

//本页中含有的函数一览


//assert_used();ctype_used();locale_used();math_used();
//stdarg_used();stddef_used();signal_used();setjmp_used();
//string_used();stdlib_used();stdio_used();